<template> 
  <a-row class="header-box">
    <a-page-header
      :title="$route.meta.title"
    >
    </a-page-header>
  </a-row>
  <a-divider :style="{marginTop:0}" />
  <a-alert
    message="说明："
    type="info"
    show-icon
  > 
    <template v-slot:icon><smile-outlined /></template>
    <template #description>
      <div>系统的基础配置。</div>
    </template>
  </a-alert>
  <a-button type="primary" @click="toResetPass" size="small" style="margin-top: 10px;">
    修改密码
  </a-button>
  <a-divider />
  <!-- 数据表格 -->
  <a-row class="form-box">
    <a-col :span="16">
      <a-form ref="form" :model="form" :rules="rules" :label-col="labelCol" :wrapper-col="wrapperCol">
        <a-form-item label="系统版本">
          {{ form.version }}
          <a v-if="newVersion" @click="doUpdate">{{ '最新的版本:' + newVersion }}</a>
        </a-form-item>
        <a-form-item label="数据库">
          {{ form.dbUrl }}
        </a-form-item>
        <a-form-item label="配置目录">
          {{ form.configPath }}
        </a-form-item>
        <a-form-item label="管理目录">
          {{ form.managePath }}
        </a-form-item>
        <!-- <a-form-item label="目录映射" name="managePathHost">
          <a-input-group>
          <a-input addon-before="管理目录" v-model:value="form.managePath" placeholder="" disabled/>
          <a-input addon-before="实际目录" v-model:value="form.managePathHost" @blur="textTrim('managePathHost')" placeholder="">
            <template #suffix>
              <a-tooltip title="1.指定系统可以管理的目录；2.Docker运行本系统时无需配置。">
                <InfoCircleOutlined />
              </a-tooltip>
            </template>
          </a-input>
        </a-input-group>
        </a-form-item> -->
        <!-- <a-form-item label="媒体库基础目录" name="libraryPath">
          <a-input v-model:value="form.libraryPath" placeholder="" readonly>
            <template #suffix>
              <FolderOpenOutlined @click="folderSelectShow=true"/>
            </template>
          </a-input>
        </a-form-item> -->
      </a-form>
    </a-col>
    
    <a-divider orientation="left" class="extra-title">通知设置</a-divider>
    <a-col :span="16">
      <a-form ref="notifyForm" :model="notifyForm" :label-col="labelCol" :wrapper-col="wrapperCol">
        <a-form-item label="BARK_PUSH" name="BARK_PUSH">
          <a-input v-model:value="notifyForm.bark.BARK_PUSH" placeholder="">
            <template #suffix>
              <a-tooltip title="此处填你BarkAPP的信息(IP/设备码，例如：https://api.day.app/XXXXXXXX)">
                <InfoCircleOutlined />
              </a-tooltip>
            </template>
          </a-input>
        </a-form-item>
        <a-form-item label="BARK_ICON" name="BARK_ICON">
          <a-input v-model:value="notifyForm.bark.BARK_ICON" placeholder="">
            <template #suffix>
              <a-tooltip title="BARK app推送图标,自定义推送图标(需iOS15或以上)">
                <InfoCircleOutlined />
              </a-tooltip>
            </template>
          </a-input>
        </a-form-item>
        <a-form-item label="BARK_SOUND" name="BARK_SOUND">
          <a-input v-model:value="notifyForm.bark.BARK_SOUND" placeholder="">
            <template #suffix>
              <a-tooltip title="BARK app推送铃声,铃声列表去APP查看复制填写">
                <InfoCircleOutlined />
              </a-tooltip>
            </template>
          </a-input>
        </a-form-item>
        <a-form-item label="BARK_GROUP" name="BARK_GROUP">
          <a-input v-model:value="notifyForm.bark.BARK_GROUP" placeholder="">
            <template #suffix>
              <a-tooltip title="BARK app推送消息的分组, 默认为:TorrentManger">
                <InfoCircleOutlined />
              </a-tooltip>
            </template>
          </a-input>
        </a-form-item>
      </a-form>
    </a-col>

    
    <a-col :span="16" align='center'>
      <a-space>
        <!-- <a-button @click="loadData">
          <template v-slot:icon><UndoOutlined/></template>
          重置
        </a-button> -->
        <a-button type="primary" @click="saveNotifyConfig">
          <template v-slot:icon><SaveFilled/></template>
          保存
        </a-button>
      </a-space>
    </a-col>
  </a-row>
  <AuthResetPasskey ref="resetModal" :success='resetOk'/>
  <!-- 路径选择 -->
  <!-- <a-modal v-model:visible="folderSelectShow" title="选择目录" @ok="getSelectedFolder">
    <FileSelector ref="refFileSelector"/>
  </a-modal> -->
  <a-drawer
    title="更新日志"
    placement="top"
    :closable="false"
    :visible="updating"
    height="100%"
  >
    <pre>{{ updateLog }}</pre>
    <a-button type="primary" @click="restart" :loading="restarting" :disabled="!restartAble">
      <!-- <template v-slot:icon><ReloadOutlined/></template> -->
      返回更新日志后，点击重启
    </a-button>
  </a-drawer>
</template>

<script>
import ConfigApi from '../../api/ConfigApi.js'
import { SmileOutlined, UndoOutlined, SaveFilled, ReloadOutlined, FolderOpenOutlined, InfoCircleOutlined } from '@ant-design/icons-vue'
import { Modal } from 'ant-design-vue';
import AuthResetPasskey from '../Auth/ResetPasskey.vue'
import FileSelector from '../components/FileSelector.vue'
import { ref } from 'vue';
export default {
  name: 'config',
  components: {
    SmileOutlined,
    UndoOutlined,
    SaveFilled,
    ReloadOutlined,
    AuthResetPasskey,
    FolderOpenOutlined,
    InfoCircleOutlined,
    FileSelector
  },
  setup() {
    const refFileSelector = ref()
    const folderSelected = () => {
      return refFileSelector.value.selectedKeys
    }
    return {
      refFileSelector, folderSelected
    }
  },
  data() {
    return {
      module: 'config',
      labelCol: { span: 5 },
      wrapperCol: { span: 19 },
      dataLoading:false, form:{}, folderSelectShow: false,
      rules: {
        name: [
          { required: true, message: '请填写站点名称', trigger: 'blur' }
        ]
      },
      newVersion: '',
      updating: false, updateCount: 0, updateLog: '', restartAble: false, restarting: false,
      notifyForm:{
        bark:{}
      }
    }
  },
  mounted() {
    this.loadData()
    this.checkUpdate()
  },
  methods: {
    textTrim(col) {
      this.form[col] = this.form[col] ? this.form[col].trim() : ''
      // console.log(`'${this.form[col]}'`)
    },
    getSelectedFolder() {
      this.form.libraryPath = this.folderSelected()[0]
      this.folderSelectShow = false
    },
    toSave() {
      ConfigApi.set(this.form).then(response=>{
        if (response.data.code === 1) {
          this.form = response.data.data
          this.$message.success("保存成功")
        } else {
          this.$message.error(`保存失败：${response.data.message}`)
        }
      }) 
    },
    loadData() {
      this.dataLoading = true
      ConfigApi.get().then(response=>{
        if (response.data.code === 1) {
          this.form = response.data.data
          if (this.form.notify) {
            this.notifyForm = this.form.notify
          }
        } else {
          this.$message.error(`数据加载失败：${response.data.message}`)
        }
      }).catch((error)=>{
        this.$message.error(`数据加载失败：${error.message}`)
      }).then(()=>{
        this.dataLoading = false
      })
    },
    toResetPass() {
      this.$refs.resetModal.open()
    },
    resetOk() {

    },
    checkUpdate(){
      ConfigApi.checkUpdate().then(response=>{
        if (response.data.code === 1) {
          this.newVersion = response.data.data.version
        } else {
          this.$message.error(`版本更新检测失败：${response.data.message}`)
        }
      }).catch((error)=>{
        this.$message.error(`版本更新检测失败：${error.message}`)
      })
    },
    doUpdate() {
      const that = this
      const content = this.newVersion === this.form.version ? '当前版本无需更新' : '发现新的可用版本，建议保持更新！'
      // const okText = this.newVersion === this.form.version ? '好的' : '更新'
      Modal.confirm({
        title: '更新提示',
        content: content,
        okText: '更新',
        cancelText: '',
        onOk() {
          that.updating = true
          that.updateCoun = 0
          // 计时
          that.updateLog = `更新中,请耐心等待... ${ that.updateCount }秒`
          const countDown = setInterval(()=>{
            that.updateCount += 1
            that.updateLog = `更新中,请耐心等待... ${ that.updateCount }秒`
          },1000)
         
          ConfigApi.doUpdate().then(response=>{
            if (response.data.code === 1) {
              that.updateLog = response.data.data
              that.restartAble = true
            } else {
              that.$message.error(`版本更新失败：${response.data.message}`)
            }
          }).catch((error)=>{
            that.$message.error(`版本更新失败：${error.message}`)
          }).then(()=>{
            clearInterval(countDown)
          })
        }
      });
    },
    restart() {
      ConfigApi.restart().then(response=>{
        if (response.data.code === 1) {
          this.restarting = true
          setTimeout(()=>{
            window.location.reload()
          }, 3000)
        } else {
          this.$message.error(`重启失败：${response.data.message}`)
        }
      }).catch((error)=>{
        that.$message.error(`重启失败：${error.message}`)
      })
    },
    reloadPage() {
      window.location.reload()
    },
    async checkAppAlive() {
      let rst = false
      try {
        await ConfigApi.get()
        rst = true
      } catch(err) {}
      return rst
    },
    saveNotifyConfig() {
      ConfigApi.set({notify: JSON.stringify(this.notifyForm)}).then(response=>{
        if (response.data.code === 1) {
          this.$message.success("保存成功")
        } else {
          this.$message.error(`保存失败：${response.data.message}`)
        }
      }) 
    }
  }
}
</script>